package mylab.commons.pool;
import org.apache.commons.pool.ObjectPool;
import java.io.Reader; 
import java.io.IOException; 
import java.util.NoSuchElementException;

public class ReaderUtil { 

	private ObjectPool pool;
	public ReaderUtil(ObjectPool pool) 
	{         
		this.pool = pool;    	
	}
	
	 public String readToString(Reader in) throws NoSuchElementException, IllegalStateException, Exception {
		 StringBuffer buf = null;
		 try {
			 buf = (StringBuffer) pool.borrowObject();
			 for(int c = in.read(); c != -1; c = in.read())
			 {
				 buf.append((char)c);
			 }
			 return buf.toString();
			
		 }catch(IOException e) { 
			 throw e;
		 }catch(Exception e){
			 throw new RuntimeException("Unable to borrow buffer from pool" + e.toString());
		 }finally{
			 try{
				 in.close();
			 }catch(Exception e){
			 }
			 try{
				 if(buf != null)
				 {
					 pool.returnObject(buf);
				 }
			 }catch (Exception e){
			 }
		 }
	 }
}